package com.jeesite.modules.wx.TemplateMsg;

import com.jeesite.common.io.PropertiesUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.kj.api.wechatUtils.TokenUtils;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.wxaapp.WxaConfig;
import com.jfinal.wxaapp.WxaConfigKit;
import com.jfinal.wxaapp.api.WxaSubscribeMsgApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 微信发送模板消息https://mp.weixin.qq.com/advanced/tmplmsg?action=faq&token=255343404&lang=zh_CN
 * hzy 2020-03-26
 */
public class WxTemplateMsgUtils {
    private final static Logger logger = LoggerFactory.getLogger(WxTemplateMsgUtils.class);
    /**
     * 微信发送模板消息
     * @param openId 微信开放ID
     * @param templateId 模板id
     * @param url 点击详情跳转地址
     */
    public static String sendByTemplate(String templateId, String openId,  String url, WxaSubscribeMsgApi.SubTemplateItem subTemplateItem){
        if(StringUtils.isBlank(openId) || StringUtils.isBlank(templateId)){
            return "templateId或openId不能为空";
        }
        PropertiesUtils props = PropertiesUtils.getInstance();
        String appid = props.getProperty("wx.service.appId");
        String secret = props.getProperty("wx.service.appSecret");
        WxaConfig wc = new WxaConfig();
        wc.setAppId(appid);
        wc.setAppSecret(secret);
        WxaConfigKit.setWxaConfig(wc);
        String msg = "";
        try {
            ApiResult result = WxaSubscribeMsgApi.send(openId, templateId, subTemplateItem, url);
            if(!result.getErrorCode().equals(0)){
                msg = result.getErrorMsg();
            }
        }catch (Exception e){
            msg = e.getMessage();
        }
        return msg;
    }

    public static void main(String[] args){
        WxaSubscribeMsgApi wxaSubscribeMsgApi = new WxaSubscribeMsgApi();
        WxaSubscribeMsgApi.SubTemplateItem subTemplateItem = wxaSubscribeMsgApi.new SubTemplateItem();
        subTemplateItem.put("thing1", wxaSubscribeMsgApi.new Item("允许参与"));
        subTemplateItem.put("thing2", wxaSubscribeMsgApi.new Item("IJPay 线下聚会"));
        subTemplateItem.put("thing3", wxaSubscribeMsgApi.new Item("2020-02-02 14:30"));
        WxTemplateMsgUtils.sendByTemplate("0Kyul8FoBFVD-bQo30IMQ5H_4zfqGULfhkOrSAM4Swc", "omukY0YdHhNU47zJigOhMHfIHYPI", "pages/index", subTemplateItem);
    }

}
